package com.tonann.web.api.service;


import com.alibaba.fastjson2.JSONObject;
import com.tonann.common.core.domain.AjaxResult;
import com.tonann.web.api.service.model.*;
import org.springframework.http.*;
import org.springframework.stereotype.Service;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class WeiYunApi {

    RestTemplate restTemplate = new RestTemplate();

    String baseUrl = "http://api.weiyuzn.com/";

    public WeiYunAuth getAuthorization() {
        String url = baseUrl + "v3/Authorizations";
        // 设置请求Header
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);

        // 设置请求参数为JSON格式
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("uname", "15692165285");
        jsonObject.put("pwd", "123456");

        // 创建请求实体
        HttpEntity<String> requestEntity = new HttpEntity<>(jsonObject.toString(), headers);
        ResponseEntity<String> responseEntity = restTemplate.exchange(url, HttpMethod.POST, requestEntity, String.class);
        String result = responseEntity.getBody();
        WeiYunAuth auth = JSONObject.parseObject(result, WeiYunAuth.class);
        return auth;
    }

    public AjaxResult getData() {
        WeiYunAuth auth = this.getAuthorization();
        if (auth != null && auth.getData() != null && auth.getData().getAccess_token() != null) {
            List<Integer> homeIdList = this.getHomeIdList(auth.getData().getAccess_token());
            Map<Integer, List<WeiYunRoomsData>> roomMap = new HashMap<>();
            Map<Integer, List<WeiYunDevicesData>> deviceMap = new HashMap<>();
            List<WeiYunAlarmRowData> alarmRowData = new ArrayList<>();
            if (!homeIdList.isEmpty()) {
                for (Integer homeId : homeIdList) {
                    List<WeiYunRoomsData> data = this.getRoomsList(auth.getData().getAccess_token(), homeId);
                    if (data != null && !data.isEmpty()) {
                        roomMap.put(homeId, data);
                    }
                    List<WeiYunDevicesData> devicesData = this.getDevicesList(auth.getData().getAccess_token(), homeId);
                    if (data != null && !data.isEmpty()) {
                        deviceMap.put(homeId, devicesData);
                    }
                    alarmRowData = this.getAlarmList(auth.getData().getAccess_token(), homeId);
                }
            }
            int overvoltage = 0;  //过压
            int overload = 0; // 过载
            int leakage = 0; // 漏电
            Map<String, RoomStatus> roomStatusMap = new HashMap<>();
            for (List<WeiYunRoomsData> roomsDataList : roomMap.values()) {
                for (WeiYunRoomsData data : roomsDataList) {
                    if (data.getRoomName() != null && !data.getRoomName().equals("默认")) {
                        RoomStatus roomStatus = new RoomStatus();
                        roomStatus.setRoomName(data.getRoomName());
                        roomStatusMap.put(data.getRoomName(), roomStatus);
                    }
                }
            }
            for (List<WeiYunDevicesData> devicesDataList : deviceMap.values()) {
                for (WeiYunDevicesData data : devicesDataList) {
                    if (data.getRoomName() != null) {
                        RoomStatus roomStatus = roomStatusMap.get(data.getRoomName());
                        if (data.getCategory() != null && data.getDevNo() != null) {
                            WeiYunDeviceStatus deviceStatus = this.getDevicesStatus(auth.getData().getAccess_token(), data.getCategory(), data.getDevNo());
                            if (deviceStatus != null && deviceStatus.getData() != null) {
                                List<WeiYunDeviceStatusData> deviceStatusData = deviceStatus.getData();
                                for (WeiYunDeviceStatusData statusData : deviceStatusData) {
                                    if (statusData.getName().equals("总路")) {
                                        List<WeiYunDeviceStatusDataStatus> statusDataStatuses = statusData.getStates();
                                        for (WeiYunDeviceStatusDataStatus dataStatus : statusDataStatuses) {
                                            if (dataStatus.getName() == null) {
                                                continue;
                                            }
                                            BigDecimal bigDecimal = new BigDecimal("0");
                                            if (dataStatus.getValue() != null) {
                                                bigDecimal = new BigDecimal(dataStatus.getValue());
                                            }
                                            if (dataStatus.getScaleFactor() != null) {
                                                bigDecimal = bigDecimal.multiply(new BigDecimal(dataStatus.getScaleFactor()));
                                            }
                                            switch (dataStatus.getName()) {
                                                case "电流":
                                                    roomStatus.setCurrent(bigDecimal.toString());
                                                    break;
                                                case "电压":
                                                    roomStatus.setVoltage(bigDecimal.toString());
                                                    break;
                                                case "有功功率":
                                                    roomStatus.setActivePower(bigDecimal.toString());
                                                    break;
                                                case "用电量":
                                                    roomStatus.setPowerConsumption(bigDecimal.toString());
                                                    break;
                                                case "漏电电流":
                                                    roomStatus.setLeakCurrent(bigDecimal.toString());
                                                    break;
                                                case "频率":
                                                    roomStatus.setFrequence(bigDecimal.toString());
                                                    break;
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            }
            for (WeiYunAlarmRowData data : alarmRowData) {
                String title = data.getTitle();
                if (title != null) {
                    if (title.contains("过载")) {
                        overload++;
                    } else if (title.contains("过压")) {
                        overload++;
                    } else if (title.contains("漏电")) {
                        leakage++;
                    }
                    String room = data.getRoom();
                    if (room != null) {
                        RoomStatus roomStatus = roomStatusMap.get(room);
                        if (roomStatus != null) {
                            switch (title) {
                                case "过载报警":
                                    roomStatus.setOverload("1");
                                    break;
                                case "短路报警":
                                    roomStatus.setShortCircuit("1");
                                    break;
                                case "漏电报警":
                                    roomStatus.setLeakage("1");
                                    break;
                                case "欠压报警":
                                    roomStatus.setUndervoltage("1");
                                    break;
                                case "过压报警":
                                    roomStatus.setOvervoltage("1");
                                    break;
                                case "温度报警":
                                    roomStatus.setOvertemp("1");
                                    break;
                                case "过功率报警":
                                    roomStatus.setOverPower("1");
                                    break;
                                case "过用电量报警":
                                    roomStatus.setQuantityElectricity("1");
                                    break;
                                case "打火报警":
                                    roomStatus.setStrike("1");
                                    break;
                                case "过载故障":
                                    roomStatus.setOverload("1");
                                    break;
                                case "短路故障":
                                    roomStatus.setShortCircuit("1");
                                    break;
                                case "漏电故障":
                                    roomStatus.setLeakage("1");
                                    break;
                                case "欠压故障":
                                    roomStatus.setUndervoltage("1");
                                    break;
                                case "过压故障":
                                    roomStatus.setOvervoltage("1");
                                    break;
                                case "高过压故障":
                                    roomStatus.setOverpressure("1");
                                    break;
                                case "温度故障":
                                    roomStatus.setOvertemp("1");
                                    break;
                                case "硬件漏电故障":
                                    roomStatus.setHardwareLeakage("1");
                                    break;
                                case "过功率故障":
                                    roomStatus.setOverPower("1");
                                    break;
                                case "过用电量故障":
                                    roomStatus.setQuantityElectricity("1");
                                    break;
                                case "恶性负载故障":
                                    roomStatus.setMalignantLoad("1");
                                    break;
                                case "打火故障":
                                    roomStatus.setStrike("1");
                                    break;
                                case "恶性负载报警":
                                    roomStatus.setMalignantLoad("1");
                                    break;
                            }
                        }
                    }
                }
            }
            WeiYunVO vo = new WeiYunVO();
            vo.setLeakage(leakage);
            vo.setOverload(overload);
            vo.setOvervoltage(overvoltage);
            vo.setRoomStatusList(roomStatusMap.values());
            return AjaxResult.success(vo);
        }
        return AjaxResult.error("无数据");
    }

    public List<Integer> getHomeIdList(String accessToken) {
        List<Integer> homeIdList = new ArrayList<>();
        String url = baseUrl + "v3/homes";
        // 设置请求Header
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);
        headers.add("Authorization", accessToken);
        // 创建请求实体
        HttpEntity<String> requestEntity = new HttpEntity<>(headers);
        ResponseEntity<String> responseEntity = restTemplate.exchange(url, HttpMethod.GET, requestEntity, String.class);
        String result = responseEntity.getBody();
        if (result != null) {
            WeiYunHomes weiYunHomes = JSONObject.parseObject(result, WeiYunHomes.class);
            if (weiYunHomes != null && weiYunHomes.getData() != null) {
                List<WeiYunHomesData> dataList = weiYunHomes.getData();
                for (WeiYunHomesData data : dataList) {
                    homeIdList.add(data.getHomeId());
                }
            }
        }
        return homeIdList;
    }

    public List<WeiYunRoomsData> getRoomsList(String accessToken, Integer homeId) {
        List<WeiYunRoomsData> roomsList = new ArrayList<>();
        String url = baseUrl + "v3/rooms?homeId=" + homeId;
        // 设置请求Header
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);
        headers.add("Authorization", accessToken);
        // 创建请求实体
        HttpEntity<String> requestEntity = new HttpEntity<>(headers);
        ResponseEntity<String> responseEntity = restTemplate.exchange(url, HttpMethod.GET, requestEntity, String.class);
        String result = responseEntity.getBody();
        if (result != null) {
            WeiYunRooms weiYunRooms = JSONObject.parseObject(result, WeiYunRooms.class);
            if (weiYunRooms != null && weiYunRooms.getData() != null) {
                List<WeiYunRoomsData> dataList = weiYunRooms.getData();
                for (WeiYunRoomsData data : dataList) {
                    roomsList.add(data);
                }
            }
        }
        return roomsList;
    }

    public List<WeiYunDevicesData> getDevicesList(String accessToken, Integer homeId) {
        List<WeiYunDevicesData> devicesDataList = new ArrayList<>();
        String url = baseUrl + "v4/devices?homeId=" + homeId;
        // 设置请求Header
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);
        headers.add("Authorization", accessToken);
        // 创建请求实体
        HttpEntity<String> requestEntity = new HttpEntity<>(headers);
        ResponseEntity<String> responseEntity = restTemplate.exchange(url, HttpMethod.GET, requestEntity, String.class);
        String result = responseEntity.getBody();
        if (result != null) {
            WeiYunDevices weiYunDevices = JSONObject.parseObject(result, WeiYunDevices.class);
            if (weiYunDevices != null && weiYunDevices.getData() != null) {
                List<WeiYunDevicesData> dataList = weiYunDevices.getData();
                for (WeiYunDevicesData data : dataList) {
                    devicesDataList.add(data);
                }
            }
        }
        return devicesDataList;
    }

    public List<WeiYunAlarmRowData> getAlarmList(String accessToken, int homeId) {
        List<WeiYunAlarmRowData> alarmDataList = new ArrayList<>();

        int pages = 0;
        int pageSize = 1000;
        List<WeiYunAlarmRowData> alarmRowDataList = new ArrayList<>();
        do {
            alarmRowDataList = this.getAlarmData(accessToken, pages, pageSize, homeId);
            alarmDataList.addAll(alarmRowDataList);
        } while (alarmRowDataList.size() >= pageSize);
        return alarmDataList;
    }

    private List<WeiYunAlarmRowData> getAlarmData(String accessToken, int pages, int pageSize, int homeId) {
        List<WeiYunAlarmRowData> alarmDataList = new ArrayList<>();
        String url = baseUrl + "v3/devices/warning/" + pages + "/" + pageSize + "?homeId=" + homeId + "&status=0";
        // 设置请求Header
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);
        headers.add("Authorization", accessToken);
        // 创建请求实体
        HttpEntity<String> requestEntity = new HttpEntity<>(headers);
        ResponseEntity<String> responseEntity = restTemplate.exchange(url, HttpMethod.GET, requestEntity, String.class);
        String result = responseEntity.getBody();
        if (result != null) {
            WeiYunAlarm weiYunAlarm = JSONObject.parseObject(result, WeiYunAlarm.class);
            if (weiYunAlarm != null && weiYunAlarm.getData() != null) {
                List<WeiYunAlarmRowData> dataList = weiYunAlarm.getData().getRows();
                for (WeiYunAlarmRowData data : dataList) {
                    alarmDataList.add(data);
                }
            }
        }
        return alarmDataList;
    }

    private WeiYunDeviceStatus getDevicesStatus(String accessToken, String category, String devno) {
        WeiYunDeviceStatus deviceStatus = null;
        String url = baseUrl + "v4/devices/breaker/" + category + "/" + devno;
        // 设置请求Header
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);
        headers.add("Authorization", accessToken);
        // 创建请求实体
        HttpEntity<String> requestEntity = new HttpEntity<>(headers);
        ResponseEntity<String> responseEntity = restTemplate.exchange(url, HttpMethod.GET, requestEntity, String.class);
        String result = responseEntity.getBody();
        if (result != null) {
            deviceStatus = JSONObject.parseObject(result, WeiYunDeviceStatus.class);
        }
        return deviceStatus;
    }
}
